import React, { VFC, useEffect, useState} from "react"
import { Form, Input, Button, Upload, message, Modal, Select } from 'antd';
import { UploadOutlined } from '@ant-design/icons';

import { uploadFile, editCourseware, saveCourseware} from '@services/manager'
import { FILe_URL } from "@tools/config";
import {checkUploadFile, pick} from '@tools/utils'
import { GetDIC } from '@api/index'

const FormItem = Form.Item;
const { TextArea } = Input;
const { Option } = Select;

type PropsType = {
    dataInfo?:any[]|null
    onCancel:() => void
    isVisible:boolean
}
const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 16 },
};

const Edit:VFC<PropsType> = props => {
    const initFormInfo = {
        name:undefined,
        pic:undefined,
        type:'1',
        size:undefined,
        introductions:undefined,
    }
    const {dataInfo, isVisible, onCancel} = props;
    const [formInfo, setFormInfo] = useState<any>(initFormInfo);
    const coursewareTypeList = GetDIC('coursewareType');
    const [defaultFileType, setDefaultFileType] = useState<any>('1');
    const [isRequest, setisRequest] = useState(false)
    const [fileList, setFileList] = useState<any>()
    useEffect(()=>{
        if(dataInfo) setFormInfo(dataInfo)
    }, []);
    // 修改输入框值
    const onChange = (e:any, type:string) => {
        setFormInfo({
            ...formInfo,
            [type]: e?.target?e.target.value:e
        })
    }
    // 文件上传前校验
    const beforeUpload = (file:any)=> {
        // 1: "音频", 2: "视频", 3: "文档"
        return new Promise((resolve, reject)=>{
            const fileType = defaultFileType==1?'audio':defaultFileType==2?'video':'document';
            if(checkUploadFile(file, fileType)){
                // _uploadFile(file)
                return resolve(file)
            }else{
                return reject(file)
            } 
        })
    }
    // 上传图片
    const _uploadFile = async (e: string | Blob) => {
        const _size = e.size / 1024 / 1024
        const formData = new FormData();
        formData.append("file", e);
        const params = {
            subject: 'sys',
            isNewFileName: 0
        };
        const { data, status } = await uploadFile(params, formData)
        if(status == '0'){
            const {fileName} = data;
            setisRequest(true)
            setFormInfo({
                ...formInfo,
                pic: fileName,
                size: _size.toFixed(3)
            })
        }
    }
    // 提交表单数据
    const submit = async () => {
        const params = pick(formInfo, [
            "id",
            "name",
            "pic",
            "type",
            "introductions",
            "size"
        ]);
        if(!params.name){
            message.error('请输入小组名称');
            return
        }
        const method = formInfo.id ? editCourseware: saveCourseware
        const { data, status } = await method(params)
        if(status == '0'){
            message.success('提交成功');
            onCancel()
        }
    };

    const onFileChange = (info: any):void =>  {
        setFileList(info.fileList)
      }
    return (
        <Modal visible={isVisible}  title={dataInfo?"编辑":"添加"} onCancel={onCancel} footer={false}>
            <Form {...layout}>
                <FormItem label="课件名称">
                    <Input value={formInfo.name} onChange={e => onChange(e, 'name')}/>
                </FormItem>
                <FormItem label="简介">
                    <TextArea  value={formInfo.introductions} onChange={e => onChange(e, 'introductions')}/>
                </FormItem>
                <FormItem label="课件类型">
                    <Select value={formInfo.type} style={{ width: 120 }} onChange={e => {setDefaultFileType(e);onChange(e, 'type')}}>
                        {
                            Object.keys(coursewareTypeList).map( key => (
                                <Option value={key}>{coursewareTypeList[key]}</Option>
                            ))
                        }
                    </Select>
                </FormItem>
                <FormItem label="上传课件">
                    <Upload
                    maxCount={1} 
                    customRequest={()=>false}
                    fileList={fileList}
                    beforeUpload={beforeUpload}
                    onChange={onFileChange}
                    >
                        <Button icon={<UploadOutlined />}>浏览</Button>
                    </Upload>
                    {/* FILe_URL */}
                </FormItem>
                <FormItem wrapperCol={{ offset: 10, span: 16 }}>
                    <Button type="primary" onClick={submit}>提交</Button>
                </FormItem>
            </Form>
        </Modal>
    )
}
export default Edit
